package com.dongwu.manager.web;

import com.dongwu.common.dto.PagingVO;
import com.dongwu.common.dto.Result;
import com.dongwu.common.exception.BusinessException;
import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.utils.UserUtils;
import com.dongwu.common.web.BaseController;
import com.dongwu.common.web.Servlets;
import com.dongwu.manager.dto.ProductData;
import com.dongwu.manager.entity.DeviceProductRecord;
import com.dongwu.manager.entity.Product;
import com.dongwu.manager.service.AdvertisingService;
import com.dongwu.manager.service.DeviceProductRecordService;
import com.dongwu.manager.service.ProductService;
import com.dongwu.security.entity.User;
import com.dongwu.security.service.IUserService;
import com.dongwu.security.utils.SecurityUtils;
import com.gexin.fastjson.JSON;
import com.google.common.collect.Lists;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manager/product")
public class ProductController extends BaseController<Product, String> {
	@Autowired
	private ProductService productService;
	@Autowired
	private DeviceProductRecordService deviceProductRecordService;
	@Autowired
	private IUserService iuService;
	@Autowired
	private AdvertisingService advertisingService;
	
	@Value("${dongwu.ProductDetailServer}")
	private String ProductDetailServer;

//	@RequestMapping(value = "/findSort")
//	public List<Product> testSort() {
//		Sort sort = new Sort(Sort.Direction.ASC, "id");
//		List<Product> list = productService.findBySort(sort);
//		return list;
//	}

	/**
	 * 从云科导入商品
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/import")
	public String ykImpl(Model model) {
		User user = iuService.findByLoginName(UserUtils.getUserLoginName());
		model.addAttribute(user);
		return getPagePath("product-import");
	}

	/**
	 * 从云科同步商品
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/sync")
	public String ykSync(Model model) {
		User user = iuService.findByLoginName(UserUtils.getUserLoginName());
		model.addAttribute(user);
		return getPagePath("product-sync");
	}
	/**
	 * 跳转到excel导入页
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/Excelimport")
	public String ExcelImpl(Model model) {
		User user = iuService.findByLoginName(UserUtils.getUserLoginName());
		model.addAttribute(user);
		return getPagePath("product-importForExcel");
	}

	private ProductData getProductData(Row row) {
		String name = getValue(row.getCell(0), "0");
		String price = getValue(row.getCell(1), "0");
		String integral = getValue(row.getCell(2), "0");
		String slideImage = getValue(row.getCell(3), "0");
		String introduction = getValue(row.getCell(4), "0");
		String outSn = getValue(row.getCell(5), "0");
		String bussinesSn = getValue(row.getCell(6), "0");
		String image = getValue(row.getCell(7), "0");
		String pathurl = getValue(row.getCell(8), "0");
		String goodsid = getValue(row.getCell(9), "0");
		ProductData data = new ProductData();
		data.setName(name);
		data.setPrice(new BigDecimal(price));
		data.setRewardPoint(Long.valueOf(integral));
		data.setSlideImage(slideImage);
		data.setIntroduction(introduction);
		data.setOutSn(outSn);
		data.setBussinesSn(bussinesSn);
		data.setImage(image);
		data.setPathmobile(pathurl);
		data.setGoodsid(goodsid);
		return data;
	}

	@SuppressWarnings("deprecation")
	private String getValue(Cell hssfCell, String format) {
		if (hssfCell == null) {
			return "";
		}
		switch (hssfCell.getCellType()) {
		case Cell.CELL_TYPE_BOOLEAN:
			return hssfCell.getBooleanCellValue() ? "TRUE" : "FALSE";
		case Cell.CELL_TYPE_ERROR:
			return ErrorEval.getText(hssfCell.getErrorCellValue());
		case Cell.CELL_TYPE_FORMULA:
			return hssfCell.getCellFormula();
		case Cell.CELL_TYPE_NUMERIC:
			if (DateUtil.isCellDateFormatted(hssfCell)) {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
				return df.format(hssfCell.getDateCellValue());
			}
			DecimalFormat df = new DecimalFormat(format);
			return df.format(hssfCell.getNumericCellValue());
		case Cell.CELL_TYPE_STRING:
			return hssfCell.getStringCellValue();
		default:
			return "";
		}
	}

	/**
	 * 从excel导入商品
	 * 
	 * @param
	 * @return
	 * @return
	 */
	@SuppressWarnings("resource")
	@RequestMapping(value = "/implExcel")
	@ResponseBody
	public Result implExcel(HttpServletRequest req, MultipartFile file) {
		List<ProductData> productDatas = Lists.newArrayList();
		// 获取文件后缀名
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		try {
			InputStream inputStream = file.getInputStream();
			BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

			if (suffix.equals(".xls")) {
				// 后缀为.xls时使用2003的方法
				POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
				HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
				HSSFSheet sheet = workbook.getSheetAt(0);
				for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
					ProductData productData = this.getProductData(sheet.getRow(i));
					productDatas.add(productData);
				}
			} else if (suffix.equals(".xlsx")) {
				// 后缀为.xlsx时使用2007的方法
				XSSFWorkbook book = new XSSFWorkbook(bufferedInputStream);

				XSSFSheet sheet = book.getSheetAt(0);
				for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {
					System.err.println(sheet.getRow(i).toString());
					ProductData productData = this.getProductData(sheet.getRow(i));
					productDatas.add(productData);
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// List<ProductData> productDataPage= productDatas.subList(pageNo,
		// toIndex)
		productService.syncProduct(productDatas);
		return Result.successResult();
	}

	/**
	 * 查询云科商品
	 *
	 * @param yunkeNum
	 * @return
	 */
	@RequestMapping(value = "/searchYKProduct", method = RequestMethod.POST)
	@ResponseBody
	public Result searchYKProduct(@RequestParam(required = true) String yunkeNum,
								  @RequestParam(required = false) int pageNo, @RequestParam(required = false) int pageSize) {
		try {
			List<ProductData> productDataList = Lists.newArrayList();
			int count = productService.searchYKProduct(yunkeNum, pageNo, pageSize, productDataList);
			PagingVO paging = new PagingVO(productDataList, count, pageNo, pageSize);
			return Result.successResult(paging);
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 查询云科商品
	 *
	 * @param yunkeNum
	 * @return
	 */
	@RequestMapping(value = "/syncYKProduct", method = RequestMethod.POST)
	@ResponseBody
	public Result syncYKProduct(@RequestParam(required = true) String yunkeNum,
								  @RequestParam(required = false) int pageNo, @RequestParam(required = false) int pageSize) {
		try {
			productService.syncYKProduct(yunkeNum, pageNo, pageSize);
			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}
	/**
	 * 商品同步
	 *
	 * @param parmJson
	 * @return
	 */
	@RequestMapping(value = "/importProduct", method = RequestMethod.POST)
	@ResponseBody
	public Result syncProduct(@RequestParam(required = true) Map<String, String> parmJson) {
		// List<Map<String,Object>> a= parmJson.get("product");
		List<ProductData> productDatas = JSON.parseArray(parmJson.get("product"), ProductData.class);

		if (productDatas == null || productDatas.isEmpty()) {
			return Result.successResult();
		}
		for (ProductData p : productDatas) {
			if (p.getImage() != "") {
				p.setImage(p.getImage().replace("https", "http"));
			}
			if (p.getSlideImage() != "") {
				p.setSlideImage(p.getSlideImage().replace("https", "http"));
			}
			if (p.getIntroduction() != "") {
				p.setIntroduction(p.getIntroduction().replace("https", "http"));
			}
			p.setPathmobile(ProductDetailServer);
		}
		productService.importProduct(productDatas);
		return Result.successResult();

	}

	/**
	 * 获取当前用户的商品总数
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getcount")
	@ResponseBody
	public Result getcount(HttpServletRequest request) {
		Long dprcount = null;
		// 获取当前登录的用户
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		userDetails.getUsername();
		if (userDetails.getUsername().equals("admin")) {
			Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
			super.filterDataPermission(searchParams);
			dprcount = productService.getCount(searchParams, null)+advertisingService.getCount(searchParams, null);
		} else {
			// 获取当前登录的用户详情
			User a = iuService.findByLoginName(userDetails.getUsername());
			dprcount = productService.getCount(null, a.getId())+advertisingService.getCount(null, a.getId());
		}
		PagingVO paging = new PagingVO(new ArrayList<Product>(), Integer.parseInt(String.valueOf(dprcount)), 0, 10);
		return Result.successResult(paging);
	}

	// -----------------------------------------------------------------------------------------------商品关联删除
	/**
	 * 根据id删除单条记录
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deleteone/{id}")
	@ResponseBody
	public Result delete(HttpServletRequest request, @PathVariable("id") String id) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
		super.filterDataPermission(searchParams);
		List<DeviceProductRecord> records = deviceProductRecordService.getAllRecord(searchParams);
		try {
			if (!SecurityUtils.hasRole(this.getDeleteRole())) {
				return Result.denyResult();
			}

			productService.delete(records, id);
			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}

	/**
	 * 根据id串批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deletemany")
	@ResponseBody
	public Result deleteBatch(HttpServletRequest request, @RequestParam(value = "ids[]") String[] ids) {
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, SEARCH_PARAM_PREFIX);
		super.filterDataPermission(searchParams);
		List<DeviceProductRecord> records = deviceProductRecordService.getAllRecord(searchParams);
		try {
			if (!SecurityUtils.hasRole(this.getBatchDeleteRole())) {
				return Result.denyResult();
			}

			if (ids == null || ids.length == 0) {
				throw new BusinessException("参数为空");
			}

			productService.delete(records, ids);

			return Result.successResult();
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			logger.error(msg, e);
			return Result.errorResult(msg);
		}
	}
}
